package com.OjSystem.common.security.service;

import cn.hutool.core.lang.UUID;
import com.OjSystem.common.redis.Constants.RedisConstants;
import com.OjSystem.common.redis.service.RedisService;
import com.OjSystem.common.security.Constants.JWTConstants;
import com.OjSystem.common.security.domain.LoginUser;
import com.OjSystem.common.security.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {
    @Autowired
    private RedisService redisService;


    /**
     * 获取token
     *
     * @param userId
     * @param identity
     * @return
     */
    public String createToken(Long userId, Integer identity) {
        String userKey = UUID.fastUUID().toString();

        Map<String, Object> claim = new HashMap<>();
        claim.put(RedisConstants.LOGIN_USER_ID, userId);
        claim.put(RedisConstants.LOGIN_USER_KEY, userKey);
        String token = JwtUtil.genJwt(claim);

        // 将数据缓存到redis中
        LoginUser loginUser = new LoginUser();
        loginUser.setIdentity(identity);
        redisService.setCacheObject(RedisConstants.KEY_PREFIX + userKey, loginUser, RedisConstants.KEY_TIME_OUT, TimeUnit.MINUTES);

        return token;
    }

    /**
     * 延长token时间
     *
     * @param token
     */
    public void extendToken(String token) {
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
            if (claims == null) {
                return;
            }
        } catch (Exception e) {
            return;
        }

        String userKey = JwtUtil.getUserKey(claims);
        String tokenKey = RedisConstants.LOGIN_USER_KEY + userKey;

        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null && expire < RedisConstants.REMAIN_TIME) {
            redisService.expire(tokenKey, RedisConstants.KEY_TIME_OUT, TimeUnit.MINUTES);
        }
    }
}
